﻿using System;
using System.Linq;
using System.Threading.Tasks;
using HengTong.Model._Admin;
using HengTong.Model.Db;
using HengTong.Model.Db.Hr;
using HengTong.Model.Db.Hr.Bill;
using HengTong.Model.Db.System;
using Microsoft.EntityFrameworkCore;
using WalkingTec.Mvvm.Core;

namespace HengTong.ViewModel.Hr.SysHrOnboardingRequestBillVms;

public partial class SysHrOnboardingRequestBillBatchVm
{
    //批量删除
    public async Task<bool> DoBatchDeleteAsync()
    {
        if (Ids == null || !Ids.Any())
        {
            MSD.AddModelError(" ", "请选择要删除的员工档案");
            return false;
        }

        var transaction = await DC.Database.BeginTransactionAsync();
        try
        {
            // 将string ID转换为Guid?列表以匹配子表的PersonId类型
            var ids = Ids.Select(x => (Guid?)Guid.Parse(x)).ToList();

            // 1. 先删除 SysHrOnboardingRequestBill 相关的数据
            var mainIds = Ids.Select(Guid.Parse).ToList();

            // 获取要删除的 SysHrOnboardingRequestBill 记录的工号
            var staffNos = await DC.Set<SysHrOnboardingRequestBill>()
                .Where(b => mainIds.Contains(b.ID))
                .Select(b => b.StaffNo)
                .Where(s => !string.IsNullOrEmpty(s))
                .ToListAsync();

            // 删除学历附件表
            var onboardingEducationIds = await DC.Set<SysPersonEducation>()
                .Where(e => e.Person is SysHrOnboardingRequestBill && e.PersonId.HasValue && ids.Contains(e.PersonId))
                .Select(e => e.ID)
                .ToListAsync();

            if (onboardingEducationIds.Any())
            {
                await DC.Set<SysPersonEducationFile>()
                    .Where(f => onboardingEducationIds.Contains((Guid)f.PersonEducationId))
                    .ExecuteDeleteAsync();
            }

            // 删除 SysHrOnboardingRequestBill 的所有相关子表数据
            await DC.Set<SysPersonEducation>().Where(e =>
                    e.Person is SysHrOnboardingRequestBill && e.PersonId.HasValue && ids.Contains(e.PersonId))
                .ExecuteDeleteAsync();
            await DC.Set<SysPersonFamily>().Where(e =>
                    e.Person is SysHrOnboardingRequestBill && e.PersonId.HasValue && ids.Contains(e.PersonId))
                .ExecuteDeleteAsync();
            await DC.Set<SysPersonWork>().Where(e =>
                    e.Person is SysHrOnboardingRequestBill && e.PersonId.HasValue && ids.Contains(e.PersonId))
                .ExecuteDeleteAsync();
            await DC.Set<SysPersonResume>().Where(e =>
                    e.Person is SysHrOnboardingRequestBill && e.PersonId.HasValue && ids.Contains(e.PersonId))
                .ExecuteDeleteAsync();
            await DC.Set<SysPersonProfessionalTitle>().Where(e =>
                    e.Person is SysHrOnboardingRequestBill && e.PersonId.HasValue && ids.Contains(e.PersonId))
                .ExecuteDeleteAsync();

            // 删除 SysHrOnboardingRequestBill 主表数据
            await DC.Set<SysHrOnboardingRequestBill>().Where(p => mainIds.Contains(p.ID)).ExecuteDeleteAsync();

            // 2. 通过 FrameworkUser 查找关联的 PersonId，然后删除 SysPerson 相关数据
            if (staffNos.Any())
            {
                // 查询关联的用户ID和PersonId
                var users = await DC.Set<FrameworkUser>()
                    .Where(u => staffNos.Contains(u.ITCode))
                    .Select(u => new { u.ID, u.ITCode, u.PersonId })
                    .ToListAsync();

                var userIds = users.Select(u => u.ID).ToList();
                var userCodes = users.Select(u => u.ITCode).ToList();
                var personIds = users.Select(u => u.PersonId).Where(p => p.HasValue).Select(p => p.Value).ToList();


                if (personIds.Any())
                {
                    var personIdsNullable = personIds.Select(id => (Guid?)id).ToList();

                    // 删除员工合同的附件
                    var contractIds = await DC.Set<SysPersonContract>()
                        .Where(e => e.PersonId.HasValue && personIdsNullable.Contains(e.PersonId))
                        .Select(c => c.ID)
                        .ToListAsync();
                    if (contractIds.Any())
                    {
                        await DC.Set<SysPersonContractFile>()
                            .Where(a => contractIds.Contains((Guid)a.PersonContractId))
                            .ExecuteDeleteAsync();
                    }

                    // 删除学历附件表
                    var educationIds = await DC.Set<SysPersonEducation>()
                        .Where(e => e.PersonId.HasValue && personIdsNullable.Contains(e.PersonId))
                        .Select(e => e.ID)
                        .ToListAsync();

                    if (educationIds.Any())
                    {
                        await DC.Set<SysPersonEducationFile>()
                            .Where(f => educationIds.Contains((Guid)f.PersonEducationId))
                            .ExecuteDeleteAsync();
                    }

                    // 删除所有相关的子表数据
                    await DC.Set<SysPersonEducation>()
                        .Where(e => e.PersonId.HasValue && personIdsNullable.Contains(e.PersonId))
                        .ExecuteDeleteAsync();
                    await DC.Set<SysPersonFamily>()
                        .Where(e => e.PersonId.HasValue && personIdsNullable.Contains(e.PersonId))
                        .ExecuteDeleteAsync();
                    await DC.Set<SysPersonWork>()
                        .Where(e => e.PersonId.HasValue && personIdsNullable.Contains(e.PersonId))
                        .ExecuteDeleteAsync();
                    await DC.Set<SysPersonTrainExam>()
                        .Where(e => e.PersonId.HasValue && personIdsNullable.Contains(e.PersonId))
                        .ExecuteDeleteAsync();
                    await DC.Set<SysPersonMedical>()
                        .Where(e => e.PersonId.HasValue && personIdsNullable.Contains(e.PersonId))
                        .ExecuteDeleteAsync();
                    await DC.Set<SysPersonResume>()
                        .Where(e => e.PersonId.HasValue && personIdsNullable.Contains(e.PersonId))
                        .ExecuteDeleteAsync();
                    await DC.Set<SysPersonContract>()
                        .Where(e => e.PersonId.HasValue && personIdsNullable.Contains(e.PersonId))
                        .ExecuteDeleteAsync();
                    await DC.Set<SysPersonProfessionalTitle>()
                        .Where(e => e.PersonId.HasValue && personIdsNullable.Contains(e.PersonId))
                        .ExecuteDeleteAsync();
                }

                // 删除系统账户关联数据
                if (userIds.Any())
                {
                    // 删除用户岗位关联
                    await DC.Set<SysUserJobPosition>()
                        .Where(x => userIds.Contains((Guid)x.UserId))
                        .ExecuteDeleteAsync();

                    // 删除用户角色关联
                    await DC.Set<FrameworkUserRole>()
                        .Where(x => userCodes.Contains(x.UserCode))
                        .ExecuteDeleteAsync();

                    // 删除用户部门关联
                    await DC.Set<FrameworkUserGroup>()
                        .Where(x => userCodes.Contains(x.UserCode))
                        .ExecuteDeleteAsync();

                    // 删除用户收藏关联
                    await DC.Set<SysUserFavorite>()
                        .Where(x => userIds.Contains((Guid)x.UserId))
                        .ExecuteDeleteAsync();
                }

                // 删除 FrameworkUser 表中关联的数据
                await DC.Set<FrameworkUser>().Where(u => staffNos.Contains(u.ITCode)).ExecuteDeleteAsync();
                // 清理缓存
                if (userCodes.Any())
                {
                    await Wtm.RemoveUserCache(userCodes.ToArray());
                }

                // 删除 SysPerson 主表数据
                await DC.Set<SysPerson>().Where(p => personIds.Contains(p.ID)).ExecuteDeleteAsync();
            }

            await DC.SaveChangesAsync();

            await transaction.CommitAsync();
            return true;
        }
        catch (Exception e)
        {
            await transaction.RollbackAsync();
            MSD.AddModelError(" ", $"批量删除异常：{e.Message}");
            return false;
        }
        finally
        {
            await transaction.DisposeAsync();
        }
    }
}